@page "/users/{id}/delete"
@inherits MainBase
@inject ILogger<Delete> Logger

<LayoutPageTitle>Delete user</LayoutPageTitle>

<PageHeader
    BreadcrumbItems="@BreadcrumbItems"
    Title="Delete user"
    Description="You can delete the user below.">
</PageHeader>

@if (IsLoading)
{
    <LoadingIndicator />
}
else
{
    <div class="p-4 mb-4 bg-white border border-gray-200 rounded-lg shadow-sm 2xl:col-span-2 dark:border-gray-700 sm:p-6 dark:bg-gray-800">
        <AlertMessageError HasTopMargin="false" Message="Note: removing this user is permanent and cannot be undone. All encrypted vault data will also be removed." />
        <h3 class="mb-4 text-xl font-semibold dark:text-white mt-4">User</h3>
        <div class="mb-4">
            <label class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Id</label>
            <div class="text-gray-900 dark:text-white">@Id</div>
        </div>
        <div class="mb-4">
            <label class="block mb-2 text-sm font-medium text-gray-900 dark:text-white">Username</label>
            <div class="text-gray-900 dark:text-white">@Obj?.UserName</div>
        </div>
        <div class="flex space-x-3">
            <Button Color="danger" OnClick="DeleteConfirm">Yes, I'm sure</Button>
            <Button Color="secondary" OnClick="Cancel">No, cancel</Button>
        </div>
    </div>
}

@code {
    /// <summary>
    /// The ID of the user to display.
    /// </summary>
    [Parameter]
    public string Id { get; set; } = string.Empty;

    private bool IsLoading { get; set; } = true;
    private AliasVaultUser? Obj { get; set; }

    /// <inheritdoc />
    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        BreadcrumbItems.Add(new BreadcrumbItem { Url = "users/" + Id, DisplayName = "View user" });
        BreadcrumbItems.Add(new BreadcrumbItem { DisplayName = "Delete user" });
    }

    /// <inheritdoc />
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);

        if (firstRender)
        {
            // Load existing Obj.
            await using var dbContext = await DbContextFactory.CreateDbContextAsync();
            Obj = await dbContext.AliasVaultUsers.FindAsync(Id);

            // Hide loading spinner
            IsLoading = false;

            // Force re-render invoke so the charts can be rendered
            StateHasChanged();
        }
    }

    private async void DeleteConfirm()
    {
        if (Obj is null)
        {
            GlobalNotificationService.AddErrorMessage("Error deleting. User entry not found.", true);
            return;
        }

        GlobalLoadingSpinner.Show();

        // Add log entry.
        Logger.LogInformation("Deleted user {UserName} ({UserId}).", Obj.UserName, Obj.Id);

        await using var dbContext = await DbContextFactory.CreateDbContextAsync();
        dbContext.AliasVaultUsers.Remove(Obj);
        await dbContext.SaveChangesAsync();

        GlobalNotificationService.AddSuccessMessage("User successfully deleted.");
        GlobalLoadingSpinner.Hide();

        NavigationService.RedirectTo("users");
    }

    private void Cancel()
    {
        NavigationService.RedirectTo("users/" + Id);
    }
}
